<template>
  <ContentWrap v-loading="formLoading">
    <el-tabs v-model="activeName">
      <el-tab-pane label="基础设置" name="info">
        <InfoForm
          ref="infoRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>
      <el-tab-pane label="价格库存" name="sku">
        <SkuForm
          ref="skuRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>
      <el-tab-pane label="物流设置" name="delivery">
        <DeliveryForm
          ref="deliveryRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>
      <el-tab-pane label="商品详情" name="description">
        <DescriptionForm
          ref="descriptionRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>
      <el-tab-pane label="其它设置" name="other">
        <OtherForm
          ref="otherRef"
          v-model:activeName="activeName"
          :is-detail="isDetail"
          :propFormData="formData"
        />
      </el-tab-pane>
    </el-tabs>
    <el-form>
      <el-form-item style="float: right">
        <template v-if="isBuiltInRole && isPendingAudit">
          <el-button type="success" plain @click="handleApprove">通过</el-button>
          <el-button type="danger" plain @click="handleReject">驳回</el-button>
        </template>
        <el-button @click="close" plain>返回</el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>
</template>
<script lang="ts" setup>
import { cloneDeep } from 'lodash-es'
import { useTagsViewStore } from '@/store/modules/tagsView'
import * as ProductSpuApi from '@/api/mall/product/spu'
import { AuditApi, AuditVO } from '@/api/mall/product/audit'
import InfoForm from './InfoForm.vue'
import DescriptionForm from './DescriptionForm.vue'
import OtherForm from './OtherForm.vue'
import SkuForm from './SkuForm.vue'
import DeliveryForm from './DeliveryForm.vue'
import { convertToInteger, copyValueToTarget, floatToFixed2, formatToFraction } from '@/utils'
import { useUserStore } from '@/store/modules/user'
import { useAuditStore } from '@/store/modules/audit'
import { ElMessageBox } from 'element-plus'

defineOptions({ name: 'ProductAuditDetail' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const { push, currentRoute } = useRouter() // 路由
const { name } = useRoute() // 查询参数
const { delView } = useTagsViewStore() // 视图操作
const userStore = useUserStore() // 用户信息
const auditStore = useAuditStore()

const isBuiltInRole = computed(() => {
  const roles = userStore.getRoles
  return roles.some(role => role === 'super_admin' || role === 'tenant_admin')
})

// 新增：是否待审核状态
const isPendingAudit = computed(() => {
  const status = (auditData.value as any).auditStatus
  return status === 0
})

const props = defineProps<{
  productInfo?: string 
}>()

const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const activeName = ref('info') // Tag 激活的窗口
const isDetail = ref(false) // 是否查看详情
const infoRef = ref() // 商品信息 Ref
const skuRef = ref() // 商品规格 Ref
const deliveryRef = ref() // 物流设置 Ref
const descriptionRef = ref() // 商品详情 Ref
const otherRef = ref() // 其他设置 Ref
// SPU 表单数据
const formData = ref<ProductSpuApi.Spu>({
  name: '', // 商品名称
  categoryId: undefined, // 商品分类
  keyword: '', // 关键字
  picUrl: '', // 商品封面图
  sliderPicUrls: [], // 商品轮播图
  introduction: '', // 商品简介
  deliveryTypes: [], // 配送方式数组
  deliveryTemplateId: undefined, // 运费模版
  brandId: undefined, // 商品品牌
  specType: false, // 商品规格
  subCommissionType: false, // 分销类型
  skus: [
    {
      price: 0, // 商品价格
      marketPrice: 0, // 市场价
      costPrice: 0, // 成本价
      barCode: '', // 商品条码
      picUrl: '', // 图片地址
      stock: 0, // 库存
      weight: 0, // 商品重量
      volume: 0, // 商品体积
      firstBrokeragePrice: 0, // 一级分销的佣金
      secondBrokeragePrice: 0 // 二级分销的佣金
    }
  ],
  description: '', // 商品详情
  sort: 0, // 商品排序
  giveIntegral: 0, // 赠送积分
  virtualSalesCount: 0 // 虚拟销量
})
const auditData = ref<AuditVO>({
  id: 0,
  productId: 0,
  productName: '',
  productCategory: '',
  submitUserId: 0,
  submitUserName: '',
  submitTime: new Date(),
  auditStatus: 0,
  auditUserId: 0,
  auditUserName: '',
  auditTime: new Date(),
  auditRemark: '',
  currentVersion: 0,
  productInfo: '' as any
})

/** 驳回理由 */
const rejectReason = ref('')

/** 驳回审核 */
const handleReject = () => {
  const productName = formData.value.name
  ElMessageBox.prompt(
    `是否驳回"${productName}"的审核？<br>驳回理由：`,
    '驳回确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      inputType: 'textarea',
      inputValue: rejectReason.value,
      inputPlaceholder: '请输入驳回理由（最多100字）',
      dangerouslyUseHTMLString: true,
      inputValidator: (value) => {
        if (value && value.length > 100) {
          return '驳回理由不能超过100字'
        }
        return true
      },
      inputErrorMessage: '驳回理由格式不正确'
    }
  ).then(async ({ value }) => {
    rejectReason.value = value
    auditData.value.auditRemark = value
    auditData.value.auditStatus = 2
    // 设置审核人信息
    auditData.value.auditUserId = userStore.user?.id
    auditData.value.auditUserName = userStore.user?.nickname
    formLoading.value = true
    try {
      await AuditApi.updateAudit(auditData.value)
      message.success('审核处理完成')
      close()
    } catch (error) {
      console.error('审核处理失败:', error)
    } finally {
      formLoading.value = false
    }
  }).catch(() => {
    // 取消操作
  })
}

/** 通过审核 */
const handleApprove = () => {
  const productName = formData.value.name
  ElMessageBox.confirm(
    `是否通过"${productName}"的审核？`,
    '审核确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    formLoading.value = true
    try {
      auditData.value.auditStatus = 1
      // 设置审核人信息
      auditData.value.auditUserId = userStore.user?.id
      auditData.value.auditUserName = userStore.user?.nickname
      const deepCopyFormData = JSON.parse(auditData.value.productInfo)
    auditData.value.productInfo = JSON.stringify(deepCopyFormData)
      await AuditApi.updateAudit(auditData.value)
      message.success('审核处理完成')
      close()
    } catch (error) {
      console.error('审核处理失败:', error)
    } finally {
      formLoading.value = false
    }
  }).catch(() => {
    // 取消操作
  })
}

/** 获得详情 */
const getDetail = async () => {
  formLoading.value = true
  try {
    // 从 store 获取数据
    const audit = auditStore.currentAudit
    if (!audit) {
      message.error('商品信息不存在')
      close()
      return
    }
    // 判断是否详情页：已审核（1通过/2驳回/3撤销）都视为详情
    isDetail.value = audit.auditStatus !== 0
    const pro = typeof audit.productInfo === 'string' ? JSON.parse(audit.productInfo) as ProductSpuApi.Spu : (audit.productInfo as ProductSpuApi.Spu);
    if (Array.isArray(pro.skus)) {
      pro.skus = pro.skus.map(sku => ({
        ...sku,
        price: Number(sku.price),
        marketPrice: Number(sku.marketPrice),
        properties: sku.properties || [],
      })) as ProductSpuApi.Sku[];
    }
    // 确保 description 字段存在
    if (pro.description === undefined) {
      pro.description = ''
    }
    formData.value = pro
    auditData.value = audit
    console.log(auditData.value)
  } catch (error) {
    console.error('解析商品数据失败:', error)
    message.error('解析商品数据失败')
    close()
  } finally {
    formLoading.value = false
  }
}

/** 关闭按钮 */
const close = () => {
  // 清除 store 中的数据
  auditStore.clearCurrentAudit()
  delView(unref(currentRoute))
  push({ name: 'Audit' })
}

/** 初始化 */
onMounted(async () => {
  await getDetail()
})

watch(
  () => props.productInfo,
  (data) => {
    if (!data) return
    const parsed = typeof data === 'string' ? JSON.parse(data) : data
    copyValueToTarget(formData.value, parsed)
  },
  {
    immediate: true
  }
)
</script>
